<?php

namespace app\webactive\controller;

use app\common\cachemodel\active\Active1CouponRecord;
use app\common\cachemodel\UserCoupon;
use app\common\lib\astrolog\Astrolog;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\common\model\Recode as RecodeModel;
use app\common\model\User;
use think\Cache;
use think\Controller;
use think\Db;
use think\Env;
use think\Exception;
use think\Log;

class ActiveYearReport extends Controller
{
    protected $user = null;

    /**
     * 2022年 年报
     */
    public function report2022()
    {
        $height = input('h/d', 0);
        $zhunleshare = input('zhunleshare/d', 0);
        $config = config('year_report.2022');
        $randNum1 = array_rand($config['bizhi'][1]);
        $randNum2 = array_rand($config['bizhi'][2]);
        $randNum3 = array_rand($config['bizhi'][3]);
        $randNum4 = array_rand($config['bizhi'][4]);
        $randNum5 = array_rand($config['bizhi'][5]);

        if ($zhunleshare === 1)
        {
            $userInfo = null;
            $appType = '';
            $isShowNav = false;
            $bizhi = [];
        } else
        {
            try
            {
                $auth = new \app\api\controller\v2\Auth();
                $auth->checkRequestAuth();
                $this->user = $auth->user;
                $userInfo = $this->getUserInfo($this->user['id']);
                $zhunleshare = 0;
                $appType = $auth->headers['app-type'];
                $isShowNav = true;
                $bizhi = [
                    1 => 'https://oss.goddessxzns.com/active/year_report/2022/bizhi/' . $config['bizhi'][1][$randNum1] . '_' . $userInfo['sign'] . '.jpg',
                    2 => 'https://oss.goddessxzns.com/active/year_report/2022/bizhi/' . $config['bizhi'][2][$randNum2] . '_' . $userInfo['sign'] . '.jpg',
                    3 => 'https://oss.goddessxzns.com/active/year_report/2022/bizhi/' . $config['bizhi'][3][$randNum3] . '_' . $userInfo['sign'] . '.jpg',
                    4 => 'https://oss.goddessxzns.com/active/year_report/2022/bizhi/' . $config['bizhi'][4][$randNum4] . '_' . $userInfo['sign'] . '.jpg',
                    5 => 'https://oss.goddessxzns.com/active/year_report/2022/bizhi/' . $config['bizhi'][5][$randNum5] . '_' . $userInfo['sign'] . '.jpg',
                ];
            }
            catch (\Exception $e)
            {
                Log::write('ActiveYearReport model => report2022()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
                throw new ApiException('服务异常');
            }
        }

        return $this->fetch('activeyearreport/report2022', [
            'bizhi' => json_encode($bizhi, JSON_UNESCAPED_UNICODE),
            'user_info' => $userInfo,
            'app_type' => $appType,
            'sign' => $userInfo['sign'],
            'height' => $height,
            'is_show_nav' => $isShowNav,
            'is_app' => $zhunleshare ? 0 : 1,
            'shareTitle' => '2022年准了年度报告来啦',
            'descript' => '新的一年已经开始，2022你都在准了做过些什么呢？2023年又会有哪些好运？开启准了年度报告，总结2022，展望2023～',
            'domain' => Env::get('host.domain'),
        ]);
    }

    /**
     * 查询用户 档案、注册日期、新增档案、合盘数、合盘最高分 信息
     * @param string $uid
     * @param int $startTime 开始时间 2022-01-01 00:00:00
     * @param int $endTime 结束时间 2023-01-01 00:00:00
     * @return array
     * @throws \Exception
     */
    private function getUserInfo(string $uid = '', $startTime = 1640966400, $endTime = 1672502400): array
    {
        $year = date('Y', $startTime);
        $result = Cache::get('active_fortune_' . $year . '_' . $uid);
        if (!$result)
        {
            try
            {
                $singInfo = config('astro_new')['sign_name'];
                $result['uid'] = $uid;
                //查询用户档案
                $map = ['uid' => $uid, 'isself' => 1];
                $recode_info = (new RecodeModel())->getSelfRecode($map);
                if ($recode_info && isset($recode_info['sun']))
                {
                    $sun = explode('-', $recode_info['sun'])[0];
                    $moon = explode('-', $recode_info['moon'])[0];
                    $asc = explode('-', $recode_info['asc'])[0];
                    $result['sign'] = (int)$sun;
                    $result['sun_info'] = "日{$singInfo[$sun]} 月{$singInfo[$moon]} 升{$singInfo[$asc]}";
                    $result['name'] = $recode_info['name'];
                }

                //查询用户注册日期
                $user_info = (new User())->field('reg_time')->where(['id' => $uid])->findOrFail();
                $user_info = json_decode(json_encode($user_info, true), true);
                if ($user_info && isset($user_info['reg_time']))
                {
                    $reg_date = date('Y-m-d', $user_info['reg_time']);
                    $reg_date_arr = explode('-', $reg_date);
                    $result['reg_time_timestamp'] = $user_info['reg_time'];
                    $result['reg_time'] = "$reg_date_arr[0]年$reg_date_arr[1]月$reg_date_arr[2]日";
                    $result['from_now_day'] = round((time() - $user_info['reg_time']) / 3600 / 24);
                }

                //查询用户2022年新增了多少档案
                $result['count_record_' . $year] = Db::table('app_recode')->alias('r')
                    ->join('app_recode_info ri', 'r.id=ri.rid', 'INNER')
                    ->field('r.id,ri.create_time')
                    ->where(['r.uid' => $uid, 'r.status' => 1])
                    ->whereBetween('ri.create_time', [$startTime, $endTime])
                    ->count();

                //查询用户2022年合盘了多少次
                $result['count_synastry_' . $year] = Db::table('app_synastry_result')
                    ->where(['uid' => $uid, 'status' => 1])
                    ->whereBetween('create_time', [$startTime, $endTime])
                    ->count();

                //查询用户2022年合盘最高分
                $result['max_score_synastry_' . $year] = Db::table('app_synastry_result')
                    ->field('score')
                    ->where(['uid' => $uid, 'status' => 1])
                    ->whereBetween('create_time', [$startTime, $endTime])
                    ->max('score');
                if ($result['max_score_synastry_' . $year] && $result['max_score_synastry_' . $year] > 0)
                {
                    $synastryResultExtra = Db::table('app_synastry_result')
                        ->where(['uid' => $uid, 'status' => 1, 'score' => $result['max_score_synastry_' . $year]])
                        ->value('extra');
                    $synastryResultExtra = json_decode($synastryResultExtra, true);

                    switch (true)
                    {   // 你们的默契度已经打败了99%的小行星啦！
                        case $result['max_score_synastry_' . $year] >= 501:
                            $synastryDefeatRatio = "99%";
                            break;
                        case $result['max_score_synastry_' . $year] >= 401:
                            $synastryDefeatRatio = "98%";
                            break;
                        case $result['max_score_synastry_' . $year] >= 301:
                            $synastryDefeatRatio = "93%";
                            break;
                        case $result['max_score_synastry_' . $year] >= 200:
                            $synastryDefeatRatio = "85%";
                            break;
                        default:
                            $synastryDefeatRatio = "69%";
                    }

                    $setting = [
                        'natal' => [
                            'planet' => [
                                [1, 8.5], [1, 7.5], [1, 3.5], [1, 3.5], [1, 4], [1, 4.5], [1, 4.5], [1, 2.5], [1, 2.5], [1, 2.5],
                                [0, 0], [0, 0], [0, 0], [0, 0], [1, 2.5], [0, 0], [0, 0], [1, 2.5], [1, 2.5], [1, 2.5], [1, 2.5]
                            ],
                            'phase' => [
                                0 => [1, 0], 60 => [1, 0], 90 => [1, 0], 120 => [1, 0], 180 => [1, 0],
                                45 => [0, 0], 135 => [0, 0], 30 => [0, 0], 150 => [0, 0], 72 => [0, 0], 144 => [0, 0]
                            ],
                            'arabic' => [
                                [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0],
                                [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0],
                                [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]
                            ],
                            'h_sys' => 'p',
                            'firdaria' => 'default',
                            'bound_type' => 'default',
                            'ecliptic' => 0,
                            'profection_push_direction' => 0,
                            'decanates' => 0,
                            'ayanamsa' => 0,
                            'location_use' => 0
                        ],
                    ];

                    $astro_data = Astrolog::getInstance()->setExecPrefix(config('astrolog.prefix'))
                        ->setIsAstrolabe(false)
                        ->setRecode1($synastryResultExtra['recode2'])
                        ->setUserSetting($setting)
                        ->getTheRecodeAstro();
                    $recode2sun = explode('-', $astro_data['sun'])[0];
                    $recode2moon = explode('-', $astro_data['moon'])[0];
                    $recode2asc = explode('-', $astro_data['asc'])[0];

                    $userDes = "日{$singInfo[$recode2sun]} 月{$singInfo[$recode2moon]} 升{$singInfo[$recode2asc]}";
                    $result['max_score_synastry_' . $year . '_recode_info'] = [
                        'name' => $synastryResultExtra['recode2']['name'],
                        'avatar' => $synastryResultExtra['recode2']['avatar'] ? Util::getImgUrl($synastryResultExtra['recode2']['avatar']) : 'https://oss.goddessxzns.com/avatar_default_t2.png',
                        'sun_info' => $userDes,
                        'defeat_ratio' => $synastryDefeatRatio,
                    ];
                } else
                {
                    $result['max_score_synastry_' . $year . '_recode_info'] = null;
                }

                //查询用户使用app信息
                $result['use_app_info_' . $year] = Db::table('wechatadmin.active_2022_user_day_and_latest_ads')
                    ->field('count_day,time_date,time_latest')
                    ->where(['uid' => $uid])
                    ->find();
                if ($result['use_app_info_' . $year] && isset($result['use_app_info_' . $year]['count_day']) && $result['use_app_info_' . $year]['count_day'] > 0)
                {   // 打败了  50% 的小行星
                    switch (true)
                    {
                        case $result['use_app_info_' . $year]['count_day'] > 281:
                            $result['use_app_info_' . $year]['defeat_ratio'] = "98%";
                            break;
                        case $result['use_app_info_' . $year]['count_day'] > 101:
                            $result['use_app_info_' . $year]['defeat_ratio'] = "85%";
                            break;
                        case $result['use_app_info_' . $year]['count_day'] > 31:
                            $result['use_app_info_' . $year]['defeat_ratio'] = "76%";
                            break;
                        default:
                            $result['use_app_info_' . $year]['defeat_ratio'] = "38%";
                    }
                }

                $userTimeDateTmp = $result['use_app_info_' . $year]['time_date'] ?? null;
                if ($userTimeDateTmp)
                {
                    $userTimeDate = explode('-', $result['use_app_info_' . $year]['time_date']);
                    $userTimeLast = explode(':', $result['use_app_info_' . $year]['time_latest']);
                    $result['use_app_info_' . $year]['time_date'] = [
                        'month' => $userTimeDate[1],
                        'day' => $userTimeDate[2]
                    ];
                    $result['use_app_info_' . $year]['time_latest'] = "$userTimeLast[0]:$userTimeLast[1]";
                    //同一时间打开app的用户数
//                    $userTimeLast1 = $userTimeLast[0] . ':' . $userTimeLast[1] . ':00';
//                    $userTimeLast2 = $userTimeLast[0] . ':' . $userTimeLast[1] . ':59';
//                    $result['use_app_info_' . $year]['same_time_use_app_user_num'] = Db::table('wechatadmin.active_2022_user_day_and_latest_ads')
//                        ->where(['time_date' => $userTimeDateTmp, 'time_latest' => ['between', [$userTimeLast1, $userTimeLast2]]])
//                        ->count('uid');
                    //同一时间打开app的用户数
                    $result['use_app_info_' . $year]['same_time_use_app_user_num'] = mt_rand(5, 50);
                } else
                {
                    if ($result['use_app_info_' . $year])
                    {
                        $result['use_app_info_' . $year]['time_date'] = null;
                        $result['use_app_info_' . $year]['time_latest'] = null;
                    }
                }
                //查询用户2022年问答提问次数
                $result['user_question_num_' . $year] = Db::table('zlcr2_user_question')
                    ->field('*')
                    ->where(['uid' => $uid])
                    ->whereBetween('create_time', [$startTime, $endTime])
                    ->count();
                Cache::set('active_fortune_' . $year . '_' . $uid, $result, 604800);
            }
            catch (Exception $e)
            {
                Log::write('年度报告' . $year . '_查询用户 档案、注册日期、新增档案、合盘数、合盘最高分 等信息异常:' . $e->getMessage(), 'error', true);
            }
        }
        return $result;
    }

    /**
     * 2024年启示录
     */
    public function report2023()
    {
        // 手机状态栏高度
        $height = input('h/d', 0);

        try
        {
            $auth = new \app\api\controller\v2\Auth();
            $auth->checkRequestAuth();
            $this->user = $auth->user;
            $userInfo = $this->getUserinfo2023($this->user['id'], 2023);
            $appType = $auth->headers['app-type'];
            $header = [
                'version' => $this->request->header('version'),
                'time' => $this->request->header('time'),
                'distinct-id' => $this->request->header('distinct-id'),
                'phone-version' => $this->request->header('phone-version'),
                'app-type' => $this->request->header('app-type'),
                'did' => $this->request->header('did'),
                'access-token' => $this->request->header('access-token'),
                'model' => $this->request->header('model'),
                'sign' => $this->request->header('sign'),
            ];
        }
        catch (Exception $e)
        {
            $appType = '';
            $userInfo = [];
            $header = [];
        }

        /**
         * reg_time string 注册日期
         * from_now_day float 已注册多少天
         */
        if (!empty($userInfo))
        {
            $topicList = [
                [
                    'keyword' => '山止川行',
                    'desc' => '经历的每一次成长，都会让自己变得更强大。',
                ],
                [
                    'keyword' => '萤火之光',
                    'desc' => '即使是微弱的光芒，也能照亮黑暗的夜晚，带给希望和力量。',
                ],
                [
                    'keyword' => '青云直上',
                    'desc' => '努力拼搏，不断进取，积极向上，追求更高的成就。',
                ],
                [
                    'keyword' => '如日方升',
                    'desc' => '这正是你最好的年华，要珍惜时间，好好把握住机会向前冲。',
                ],
                [
                    'keyword' => '持之以恒',
                    'desc' => '全心全意地专注于某事，决不分心，会有意想不到的收获哦。',
                ],
                [
                    'keyword' => '乐乐陶陶',
                    'desc' => '人生是一场体验，不要让小事占据有你的情绪，一定要保持好心情。',
                ],
                [
                    'keyword' => '及时行乐',
                    'desc' => '给自己时间，不要焦虑，一步一步来，一日一日过。',
                ],
                [
                    'keyword' => '逆风执炬',
                    'desc' => '成长路上曾受过的伤，终会化作照亮前路的光。',
                ],
                [
                    'keyword' => '未来可期',
                    'desc' => '做好今天，今天就是明天，明天就是未来。',
                ],
                [
                    'keyword' => '自信不疑',
                    'desc' => '真正自信的人，总能够简单得铿锵有力。',
                ],
                [
                    'keyword' => '静待花开',
                    'desc' => '好好爱自己，盛不盛开，花都是花。',
                ],
                [
                    'keyword' => '勇毅笃行',
                    'desc' => '要大笑，要做梦，要与众不同，人生是一场伟大的冒险。',
                ],
            ];
            $userInfo['topic'] = $topicList[$userInfo['reg_time_timestamp'] % 12];
        }

        $tip_list = [
            '春花灿烂桃花开', '事业顺风顺水', '出门遇喜事儿', '天降横财',
            '人际关系洗牌期', '天降大任', '家有喜事', '感情冲刺期',
        ];


        return $this->fetch('activeyearreport/report2023', [
            'height' => $height,
            'share_url' => '',
            'img_host' => Env::get('host.photo'),
            'app_type' => $appType,
            'userinfo' => $userInfo,
            'tip_list' => $tip_list,
            'shareTitle' => '准了｜2024新年启示录',
            'descript' => '点击开启属于你的2024年运势之旅',
            'domain' => Env::get('host.domain'),
            'headers' => json_encode($header)
        ]);
    }

    private function getUserinfo2023($uid = '', $year = 2023)
    {
        $result = Cache::get('active_fortune_' . $year . '_' . $uid);
        if (!$result || !isset($result['coupon_name']) || !$result['coupon_name'])
        {
            try
            {
                //查询用户注册日期
                $user_info = (new User())->field('nickname,avatar,reg_time')->where(['id' => $uid])->findOrFail();
                $user_info = json_decode(json_encode($user_info, true), true);
                if ($user_info && isset($user_info['reg_time']))
                {
                    $result['name'] = $user_info['nickname'];
                    $user_info['avatar'] = $user_info['avatar'] ?: '';
                    $result['avatar'] = Util::getImgUrl($user_info['avatar']) ?: 'https://oss.goddessxzns.com/avatar_default_t2.png';
                    $result['reg_time_timestamp'] = $user_info['reg_time'];
                    $regDiff = (time() - $user_info['reg_time']) / 86400;
                    $result['reg_year'] = (int)($regDiff / 365);
                    $result['reg_day'] = $regDiff % 365;
                    if ($result['reg_day'] <= 0)
                    {
                        $result['reg_day'] = 1;
                    }
                }
                // 查询用户是否已领取优惠券
                $activeCouponRecordModel = new Active1CouponRecord();
                $giveCouponRecord = $activeCouponRecordModel->getCouponData(20240101, $this->user['id'], 3);
                if (isset($giveCouponRecord[1]))
                {
                    $userCcouponInfo = (new UserCoupon())->getInfoById($giveCouponRecord[1], ['c_id']);
                    $couponName = [
                        732 => '年运八折券',   // 年运八折券    优惠券ID => 获得机率
                        733 => '年运七折券',   // 年运7折券
                        731 => '年运九折券',   // 年运九折券
                        734 => '年运五折券',   // 年运5折券
                        730 => '年运免费券',   // 年运免费券
                    ];
                    //  已领取优惠券名字
                    $result['coupon_name'] = $couponName[$userCcouponInfo['c_id']];
                }
                Cache::set('active_fortune_' . $year . '_' . $uid, $result, 604800);
            }
            catch (Exception $e)
            {
                Log::write('启示录' . $year . '_查询用户 注册日期、领券 等信息异常:' . $e->getMessage(), 'error', true);
            }
        }
        return $result;
    }
}
